<?php
namespace ball;
use think\facade\Cache;
use EasyWeChat\Pay\Application as EasyPay;
use \Symfony\Component\HttpFoundation\Request as symfonyRequest;
class WechatApp{
    public static function main(){
        $app = new EasyPay([
            'mch_id' => 1713968506,
            // 商户证书
            'private_key' => app()->getRootPath(). 'extend'.DIRECTORY_SEPARATOR.'ball'.DIRECTORY_SEPARATOR.'certs'.DIRECTORY_SEPARATOR.'apiclient_key.pem',
            'certificate' => app()->getRootPath(). 'extend'.DIRECTORY_SEPARATOR.'ball'.DIRECTORY_SEPARATOR.'certs'.DIRECTORY_SEPARATOR.'apiclient_cert.pem',
             // v3 API 秘钥
            'secret_key' => 'xinjiangronghetiyuzhongxin583600',
            // v2 API 秘钥
            'v2_secret_key' => 'xinjiangronghetiyuzhongxin583500',
            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                "PUB_KEY_ID_0117139685062025042700321729002400" => app()->getRootPath(). 'extend'.DIRECTORY_SEPARATOR.'ball'.DIRECTORY_SEPARATOR.'certs'.DIRECTORY_SEPARATOR.'pubkey.pem',
            ],
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 base_uri
                // 'base_uri' => 'https://api.mch.weixin.qq.com/',
            ],
        ]);
        return $app;
    } 
    /**
     * 获取支付参数
     */
    public static function precreate($order){
        $client = self::main()->getClient();
        $response = $client->postJson('/v3/pay/transactions/jsapi',[
                'mchid'=>'1713968506',
                'appid'=>'wx8bb452105c23ec23',
                'description'=>$order['title'],
                'out_trade_no'=>$order['out_trade_no'],
                'notify_url'=> $order['notify_url'],
                'amount' => ['total'=>intval($order['order_amount']*100)],
                'payer' => ['openid'=>$order['openid']]
            
            ]);
        $prepay = $response->toArray(false);
        $utils = self::main()->getUtils();
        $config = $utils->buildMiniAppConfig($prepay["prepay_id"], 'wx8bb452105c23ec23', 'RSA');
        return $config;
    }
    /*{
        "transaction_id":"1217752501201407033233368018",
        "amount":{
            "payer_total":100,
            "total":100,
            "currency":"CNY",
            "payer_currency":"CNY"
        },
        "mchid":"1230000109",
        "trade_state":"SUCCESS",
        "bank_type":"CMC",
        "promotion_detail":[...],
        "success_time":"2018-06-08T10:34:56+08:00",
        "payer":{
            "openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
        },
        "out_trade_no":"1217752501201407033233368018",
        "appid":"wxd678efh567hg6787",
        "trade_state_desc":"支付成功",
        "trade_type":"MICROPAY",
        "attach":"自定义数据",
        "scene_info":{
            "device_id":"013467007045764"
        }
    }*/
    public static function notify(){
        $params = request()->param();
        $request = symfonyRequest::create(
            request()->url(true),
            request()->method(),
            request()->param(),
            request()->cookie(),
            [],
            request()->server(),
            request()->getContent()?:null
        );
        self::main()->setRequestFromSymfonyRequest($request);
        $server = self::main()->getServer();
        $message = $server->getRequestMessage();
        if($message->getEventType() == 'TRANSACTION.SUCCESS'){
            return $message->toArray();
        }
        return false;
    }
    public static function query($out_trade_no){
        $client = self::main()->getClient();
        $response = $client->get("/v3/pay/transactions/out-trade-no/{$out_trade_no}",['mchid'=>'1713968506']);
        return $response->toArray(false);
    }

    public static function shopping($order){

        $miniApp = new \EasyWeChat\MiniApp\Application([
            'app_id' => 'wx8bb452105c23ec23',
            'secret' => 'e9dd35243f455d23539da568d749c4ef',
            'http' => [
                'throw'  => true, 
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ]);
        $accessToken = $miniApp->getAccessToken();
        $token = $accessToken->getToken();
        $client = $miniApp->getClient();
        $response = $client->postJson("/wxa/sec/order/upload_shipping_info?access_token={token}",[
            'order_key'=>[
                'order_number_type'=>1,
                'out_trade_no'=>$order['out_trade_no'],
                'mchid'=>'1713968506'
            ],
            'logistics_type'=>2,
            'delivery_mode'=>1,
            'shipping_list'=>[
               [ 'item_desc'=>$order['title']]
            ],
            'upload_time'=>''.date('Y-m-d').'T'.date('H:i:s').'.000+08:00',
            'payer'=>[
                'openid'=>$order['openid']
            ]
        ]);
        return $response->toArray();
    }
}
